<template>
  <view class="register-container">
    <view class="register-header">
      <h2 class="register-title">创建新账号</h2>
      <p class="register-subtitle">加入我们，开始您的单词学习之旅</p>
    </view>
    
    <view class="register-form">
      <view class="form-group">
        <label for="username" class="form-label">用户名</label>
        <input
          id="username"
          v-model="formData.username"
          type="text"
          class="form-input"
          placeholder="请输入用户名"
          :disabled="isLoading"
          @keyup.enter="focusNext('email')"
        />
        <view v-if="errors.username" class="error-message">{{ errors.username }}</view>
      </view>
      
      <view class="form-group">
        <label for="email" class="form-label">邮箱</label>
        <input
          id="email"
          v-model="formData.email"
          type="email"
          class="form-input"
          placeholder="请输入邮箱"
          :disabled="isLoading"
          @keyup.enter="focusNext('password')"
        />
        <view v-if="errors.email" class="error-message">{{ errors.email }}</view>
      </view>
      
      <view class="form-group">
        <label for="password" class="form-label">密码</label>
        <view class="password-input-container">
          <input
            id="password"
            v-model="formData.password"
            :type="showPassword ? 'text' : 'password'"
            class="form-input password-input"
            placeholder="请设置密码"
            :disabled="isLoading"
            @keyup.enter="focusNext('confirmPassword')"
          />
          <button
            type="button"
            class="toggle-password-btn"
            @click="togglePassword"
            :disabled="isLoading"
            aria-label="切换密码可见性"
          >
            <i class="icon-eye" :class="{ 'icon-eye-slash': showPassword }"></i>
          </button>
        </view>
        <view class="password-strength" v-if="formData.password.length > 0">
          <view
            class="strength-bar"
            :class="passwordStrengthClass"
          ></view>
          <span class="strength-text">{{ passwordStrengthText }}</span>
        </view>
        <view v-if="errors.password" class="error-message">{{ errors.password }}</view>
      </view>
      
      <view class="form-group">
        <label for="confirmPassword" class="form-label">确认密码</label>
        <input
          id="confirmPassword"
          v-model="formData.confirmPassword"
          :type="showPassword ? 'text' : 'password'"
          class="form-input"
          placeholder="请再次输入密码"
          :disabled="isLoading"
          @keyup.enter="handleRegister"
        />
        <view v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</view>
      </view>
      
      <view class="form-group">
        <label class="agree-terms">
          <input
            type="checkbox"
            v-model="formData.agreeTerms"
            :disabled="isLoading"
          />
          <span>
            我已阅读并同意
            <a href="#" class="link" @click.prevent="showTerms">服务条款</a>
            和
            <a href="#" class="link" @click.prevent="showPrivacy">隐私政策</a>
          </span>
        </label>
        <view v-if="errors.agreeTerms" class="error-message">{{ errors.agreeTerms }}</view>
      </view>
      
      <button
        class="register-btn"
        @click="handleRegister"
        :disabled="isLoading || !isFormValid"
      >
        <span v-if="isLoading">注册中...</span>
        <span v-else>立即注册</span>
      </button>
      
      <view class="login-link">
        <span>已有账号？</span>
        <text class="link" @click="goToLogin">立即登录</text>
      </view>
    </view>
    
      <view class="register-footer">
      <p class="footer-text">使用第三方账号快速注册</p>
      <view class="social-register">
        <button class="social-btn wechat" @click="handleWechatRegister" :disabled="isLoading">
          <i class="icon-wechat"></i>
        </button>
        <button class="social-btn qq" @click="handleQQRegister" :disabled="isLoading">
          <i class="icon-qq"></i>
        </button>
        <button class="social-btn weibo" @click="handleWeiboRegister" :disabled="isLoading">
          <i class="icon-weibo"></i>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, computed, onMounted } from 'vue'

export default {
  name: 'Register',
  setup() {
    
    const formData = ref({
      username: '',
      email: '',
      password: '',
      confirmPassword: '',
      agreeTerms: false
    })
    
    const showPassword = ref(false)
    const isLoading = ref(false)
    const errors = ref({})
    
    // 表单是否有效
    const isFormValid = computed(() => {
      return formData.value.username.trim() !== '' &&
             formData.value.email.trim() !== '' &&
             formData.value.password.trim() !== '' &&
             formData.value.confirmPassword.trim() !== '' &&
             formData.value.agreeTerms &&
             Object.keys(errors.value).length === 0
    })
    
    // 密码强度检测
    const passwordStrength = computed(() => {
      const password = formData.value.password
      let strength = 0
      
      // 长度检测
      if (password.length >= 8) strength += 1
      
      // 包含小写字母
      if (/[a-z]/.test(password)) strength += 1
      
      // 包含大写字母
      if (/[A-Z]/.test(password)) strength += 1
      
      // 包含数字
      if (/\d/.test(password)) strength += 1
      
      // 包含特殊字符
      if (/[^A-Za-z0-9]/.test(password)) strength += 1
      
      return strength
    })
    
    // 密码强度样式类
    const passwordStrengthClass = computed(() => {
      const strength = passwordStrength.value
      if (strength <= 2) return 'weak'
      if (strength <= 3) return 'medium'
      return 'strong'
    })
    
    // 密码强度文本
    const passwordStrengthText = computed(() => {
      const strength = passwordStrength.value
      if (strength <= 2) return '弱'
      if (strength <= 3) return '中'
      return '强'
    })
    
    // 验证表单
    const validateForm = () => {
      const newErrors = {}
      
      // 验证用户名
      if (!formData.value.username.trim()) {
        newErrors.username = '请输入用户名'
      } else if (formData.value.username.length < 3) {
        newErrors.username = '用户名长度不能少于3位'
      } else if (formData.value.username.length > 20) {
        newErrors.username = '用户名长度不能超过20位'
      }
      
      // 验证邮箱
      if (!formData.value.email.trim()) {
        newErrors.email = '请输入邮箱'
      } else {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        if (!emailRegex.test(formData.value.email)) {
          newErrors.email = '请输入有效的邮箱地址'
        }
      }
      
      // 验证密码
      if (!formData.value.password.trim()) {
        newErrors.password = '请设置密码'
      } else if (formData.value.password.length < 6) {
        newErrors.password = '密码长度不能少于6位'
      } else if (formData.value.password.length > 20) {
        newErrors.password = '密码长度不能超过20位'
      }
      
      // 验证确认密码
      if (!formData.value.confirmPassword.trim()) {
        newErrors.confirmPassword = '请再次输入密码'
      } else if (formData.value.confirmPassword !== formData.value.password) {
        newErrors.confirmPassword = '两次输入的密码不一致'
      }
      
      // 验证服务条款
      if (!formData.value.agreeTerms) {
        newErrors.agreeTerms = '请阅读并同意服务条款和隐私政策'
      }
      
      errors.value = newErrors
      return Object.keys(newErrors).length === 0
    }
    
    // 跳转到登录页面
    const goToLogin = () => {
      uni.navigateTo({ url: '/pages/login/Login' })
    }
    
    // 处理注册
    const handleRegister = async () => {
      if (!validateForm() || isLoading.value) return
      
      isLoading.value = true
      try {
        // 模拟注册API调用
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        // 模拟成功响应
        const mockToken = 'mock_token_' + Date.now()
        
        // 保存token
        uni.setStorageSync('token', mockToken)
        
        // 显示注册成功提示
        uni.showToast({
          title: '注册成功',
          icon: 'success'
        })
        
        // 跳转到首页
        setTimeout(() => {
          uni.switchTab({ url: '/pages/home/Home' })
        }, 1500)
      } catch (error) {
        console.error('注册失败:', error)
        // 显示错误提示
        uni.showToast({
          title: error.message || '注册失败，请重试',
          icon: 'none'
        })
      } finally {
        isLoading.value = false
      }
    }
    
    // 切换密码可见性
    const togglePassword = () => {
      showPassword.value = !showPassword.value
    }
    
    // 聚焦到下一个输入框（在uni-app中，我们可以使用ref来实现）
    const focusNext = (id) => {
      // 在实际项目中，可以通过ref获取元素并调用focus方法
      // 这里暂时省略实现
      console.log('focusNext:', id)
    }
    
    // 显示服务条款
    const showTerms = () => {
      uni.showModal({
        title: '服务条款',
        content: '服务条款内容正在完善中...',
        showCancel: false
      })
    }
    
    // 显示隐私政策
    const showPrivacy = () => {
      uni.showModal({
        title: '隐私政策',
        content: '隐私政策内容正在完善中...',
        showCancel: false
      })
    }
    
    // 第三方注册处理
    const handleWechatRegister = () => {
      uni.showModal({
        title: '提示',
        content: '微信注册功能正在开发中',
        showCancel: false
      })
    }
    
    const handleQQRegister = () => {
      uni.showModal({
        title: '提示',
        content: 'QQ注册功能正在开发中',
        showCancel: false
      })
    }
    
    const handleWeiboRegister = () => {
      uni.showModal({
        title: '提示',
        content: '微博注册功能正在开发中',
        showCancel: false
      })
    }
    
    // 组件挂载时，如果已经登录则跳转到首页
    onMounted(() => {
      const token = uni.getStorageSync('token')
      if (token) {
        uni.switchTab({ url: '/pages/home/Home' })
      }
    })
    
    return {
      formData,
      showPassword,
      isLoading,
      errors,
      isFormValid,
      passwordStrengthClass,
      passwordStrengthText,
      handleRegister,
      togglePassword,
      focusNext,
      showTerms,
      showPrivacy,
      handleWechatRegister,
      handleQQRegister,
      handleWeiboRegister,
      goToLogin
    }
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.register-header {
  text-align: center;
  margin-bottom: 40px;
  color: #ffffff;
}

.register-title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}

.register-subtitle {
  font-size: 16px;
  opacity: 0.9;
}

.register-form {
  background: #ffffff;
  border-radius: 16px;
  padding: 32px;
  width: 100%;
  max-width: 420px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.form-group {
  margin-bottom: 24px;
}

.form-label {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #333333;
  margin-bottom: 8px;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.form-input:focus {
  outline: none;
  border-color: #f5576c;
  box-shadow: 0 0 0 3px rgba(245, 87, 108, 0.1);
}

.form-input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.password-input-container {
  position: relative;
}

.password-input {
  padding-right: 48px;
}

.toggle-password-btn {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  color: #999999;
}

.toggle-password-btn:hover {
  color: #f5576c;
}

.icon-eye,
.icon-eye-slash {
  display: inline-block;
  width: 20px;
  height: 20px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.icon-eye {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/></svg>');
}

.icon-eye-slash {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M17.94 17.39c-1.04-.49-1.97-1.12-2.78-1.85-.19-.18-.34-.39-.51-.61-.17-.22-.38-.43-.61-.51-.73-.81-1.36-1.74-1.85-2.78-.05-.11-.1-.22-.15-.33l2.11 2.11c.44.44 1.13.44 1.57 0 .44-.44.44-1.13 0-1.57l-1.89-1.9c.11-.11.22-.21.33-.31 1.05-.5 1.98-1.13 2.79-1.85.22-.17.43-.38.51-.61.18-.19.39-.34.61-.51.81-.73 1.74-1.36 2.78-1.85.11-.05.22-.1.33-.15l1.89 1.9c.44.44.44 1.13 0 1.57-.44.44-1.13.44-1.57 0l-2.11-2.11c.05.11.1.22.15.33.49 1.04 1.12 1.97 1.85 2.78.18.18.34.39.51.61.17.22.38.43.61.51.73.81 1.36 1.74 1.85 2.78.05.11.1.22.15.33l-1.89 1.9c-.44.44-1.13.44-1.57 0-.44-.44-.44-1.13 0-1.57l2.11-2.11c-.05-.11-.1-.22-.15-.33zM12 14c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zM14.31.36l1.42 1.42-1.42 1.42-1.42-1.42 1.42-1.42z"/></svg>');
}

.password-strength {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 8px;
}

.strength-bar {
  flex: 1;
  height: 4px;
  border-radius: 2px;
  transition: all 0.3s ease;
}

.strength-bar.weak {
  background-color: #ff4757;
  width: 30%;
}

.strength-bar.medium {
  background-color: #ffa502;
  width: 60%;
}

.strength-bar.strong {
  background-color: #2ed573;
  width: 100%;
}

.strength-text {
  font-size: 12px;
  font-weight: 600;
  color: #666666;
  min-width: 24px;
  text-align: right;
}

.error-message {
  color: #e64340;
  font-size: 12px;
  margin-top: 4px;
}

.agree-terms {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  font-size: 14px;
  color: #666666;
  cursor: pointer;
}

.agree-terms input[type="checkbox"] {
  margin-top: 2px;
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.agree-terms .link {
  color: #f5576c;
  text-decoration: none;
}

.agree-terms .link:hover {
  text-decoration: underline;
}

.register-btn {
  width: 100%;
  padding: 14px;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: #ffffff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.register-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 87, 108, 0.4);
}

.register-btn:active:not(:disabled) {
  transform: translateY(0);
}

.register-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.login-link {
  text-align: center;
  margin-top: 24px;
  font-size: 14px;
  color: #666666;
}

.login-link .link {
  color: #f5576c;
  text-decoration: none;
  font-weight: 600;
  transition: color 0.3s ease;
}

.login-link .link:hover {
  color: #f093fb;
}

.register-footer {
  margin-top: 32px;
  text-align: center;
  color: #ffffff;
}

.footer-text {
  font-size: 14px;
  margin-bottom: 16px;
  opacity: 0.9;
}

.social-register {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.social-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  color: #ffffff;
  cursor: pointer;
  transition: all 0.3s ease;
}

.social-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

.social-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.icon-wechat,
.icon-qq,
.icon-weibo {
  display: inline-block;
  width: 24px;
  height: 24px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.icon-wechat {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23ffffff"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>');
}

.icon-qq {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23ffffff"><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 14h-2v-4H8v-2h2V9h2v2h2v2h-2v4zm4-8h-2V7h2v2zm0 4h-2v-2h2v2zm-6 0h-2v-2h2v2zm-2-4V7h2v2H8z"/></svg>');
}

.icon-weibo {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23ffffff"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.99 13.38c-.53 0-.96-.43-.96-.96s.43-.96.96-.96.96.43.96.96-.43.96-.96.96zM14 9c-.76 0-1.62.44-2 1.09-1.21-1.96-3.41-3.35-5.99-3.67v2.19c1.92.28 3.61 1.38 4.99 3.09 1.39 1.71 3.08 2.81 5.01 3.09v2.19c-3.19-.43-5.75-2.59-6.73-5.53l1.38.59c.31-.88.55-1.8.71-2.74l-1.75.5c.13-1.3.85-2.41 1.9-3.07l.12-.07v2.11c.01-.02.02-.03.03-.04-.01.01-.01.02-.02.04h2.08c0-.02-.01-.03-.01-.04v-2.07l.12.07c1.05.66 1.77 1.77 1.9 3.07l-1.75-.5c.16.94.4 1.86.71 2.74l1.38-.59c-.98-2.95-3.53-5.11-6.72-5.53V5.33c2.58.32 4.78 1.71 5.99 3.67C15.62 9.44 14.76 9 14 9z"/></svg>');
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-form {
    padding: 24px;
  }
  
  .register-title {
    font-size: 24px;
  }
}

@media (max-width: 480px) {
  .register-container {
    padding: 16px;
  }
  
  .register-form {
    padding: 20px;
  }
  
  .register-title {
    font-size: 20px;
  }
  
  .register-subtitle {
    font-size: 14px;
  }
  
  .form-input {
    padding: 10px 14px;
    font-size: 14px;
  }
  
  .register-btn {
    padding: 12px;
    font-size: 14px;
  }
  
  .social-register {
    gap: 16px;
  }
  
  .social-btn {
    width: 42px;
    height: 42px;
  }
  
  .agree-terms {
    font-size: 13px;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.register-form {
  animation: fadeIn 0.5s ease-out;
}

.register-header {
  animation: fadeIn 0.5s ease-out 0.1s both;
}

.register-footer {
  animation: fadeIn 0.5s ease-out 0.2s both;
}
</style>